# -*- coding: utf-8 -*-
"""
Flask应用工厂
@api-version: 1.0.0
"""

import os
from flask import Flask, jsonify
from flask_cors import CORS
from flask_jwt_extended import JWTManager
from flask_marshmallow import Marshmallow

from backend.config import Config, DevelopmentConfig, ProductionConfig, TestingConfig
from backend.models import db
from backend.utils.response import error_response

# 配置映射
config = {
    'development': DevelopmentConfig,
    'production': ProductionConfig,
    'testing': TestingConfig,
    'default': DevelopmentConfig
}

# 初始化扩展
jwt = JWTManager()
cors = CORS()
ma = Marshmallow()

def create_app(config_name=None):
    """应用工厂函数"""
    if config_name is None:
        config_name = os.environ.get('FLASK_ENV', 'development')
    
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    
    # 初始化扩展
    db.init_app(app)
    jwt.init_app(app)
    ma.init_app(app)
    CORS(app, origins=app.config['CORS_ORIGINS'])
    
    # 注册蓝图
    from backend.routes.auth import auth_bp
    from backend.routes.user import user_bp
    from backend.routes.admin import admin_bp
    from backend.routes.share_189_routes import share_189_bp
    from backend.api.netdisk import netdisk_bp
    from backend.api.cloud_files import cloud_files_bp
    
    app.register_blueprint(auth_bp, url_prefix=app.config['API_PREFIX'])
    app.register_blueprint(user_bp, url_prefix=app.config['API_PREFIX'])
    app.register_blueprint(admin_bp, url_prefix=f"{app.config['API_PREFIX']}/admin")
    app.register_blueprint(share_189_bp)  # 189云盘分享码API，已包含/api前缀
    # 将虚拟网盘蓝图注册到 /api/netdisk 前缀，避免与其他蓝图混淆，并与前端路径保持一致
    app.register_blueprint(netdisk_bp, url_prefix=f"{app.config['API_PREFIX']}{netdisk_bp.url_prefix}")  # 虚拟网盘API
    # 云存储文件管理API
    app.register_blueprint(cloud_files_bp, url_prefix=f"{app.config['API_PREFIX']}{cloud_files_bp.url_prefix}")
    
    # 添加请求日志中间件
    @app.before_request
    def log_request_info():
        from flask import request
        print(f"[REQUEST] 收到请求: {request.method} {request.url}")
        print(f"[REQUEST] 请求路径: {request.path}")
        print(f"[REQUEST] 请求参数: {dict(request.args)}")
        print(f"[REQUEST] 请求头Authorization: {request.headers.get('Authorization', 'None')}")
    
    # 全局错误处理
    @app.errorhandler(404)
    def not_found(error):
        return jsonify({
            'code': 404,
            'success': False,
            'message': '接口不存在',
            'data': None
        }), 404
    
    @app.errorhandler(500)
    def internal_error(error):
        return jsonify({
            'code': 500,
            'success': False,
            'message': '服务器内部错误',
            'data': None
        }), 500
    
    # JWT错误处理
    @jwt.expired_token_loader
    def expired_token_callback(jwt_header, jwt_payload):
        return jsonify({
            'code': 401,
            'success': False,
            'message': 'Token已过期',
            'data': None
        }), 401
    
    @jwt.invalid_token_loader
    def invalid_token_callback(error):
        return jsonify({
            'code': 401,
            'success': False,
            'message': 'Token无效',
            'data': None
        }), 401
    
    @jwt.unauthorized_loader
    def missing_token_callback(error):
        return jsonify({
            'code': 401,
            'success': False,
            'message': '缺少Token',
            'data': None
        }), 401
    
    # 健康检查接口
    @app.route('/api/health')
    def health_check():
        return jsonify({
            'code': 200,
            'success': True,
            'message': 'Service is healthy',
            'data': {
                'version': app.config['API_VERSION'],
                'status': 'healthy'
            }
        })
    
    return app

if __name__ == '__main__':
    import logging
    # 配置根日志记录器
    logging.basicConfig(
        level=logging.DEBUG,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[
            logging.StreamHandler()
        ]
    )
    
    app = create_app()
    with app.app_context():
        db.create_all()
    app.run(host='0.0.0.0', port=5000, debug=False)